/**
 * 弹幕组件库使用示例
 * 复制这个文件到你的项目中作为参考
 */

import React, { useRef, useState, useEffect } from 'react'
import { 
  VideoBarrage, 
  useBarrage, 
  createBarrage, 
  getPreset,
  // setApiBaseUrl,
  BarrageAPI,
  type BarrageData
} from './index' // 根据你的项目路径调整

// 基础弹幕示例
export const BasicBarrageExample: React.FC = () => {
  const videoRef = useRef<HTMLVideoElement>(null)
  const [inputText, setInputText] = useState('')
  
  const { barrageRef, addBarrage, clearBarrages, activeCount, maxCapacity } = useBarrage({
    config: getPreset('default')
  })

  const handleSend = () => {
    if (!inputText.trim()) return
    
    const barrage = createBarrage(inputText, {
      color: `#${Math.floor(Math.random()*16777215).toString(16)}`,
      fontSize: 20
    })
    
    addBarrage(barrage)
    setInputText('')
  }

  return (
    <div style={{ maxWidth: '800px', margin: '0 auto', padding: '20px' }}>
      <h2>基础弹幕示例</h2>
      
      <div style={{ position: 'relative', marginBottom: '20px' }}>
        <video
          ref={videoRef}
          src="/demo-video.mp4" // 替换为你的视频路径
          controls
          style={{ width: '100%', height: '450px', objectFit: 'contain' }}
        />
        
        <VideoBarrage
          ref={barrageRef}
          videoRef={videoRef}
          config={getPreset('default')}
          enabled={true}
        />
      </div>
      
      <div style={{ display: 'flex', gap: '10px', marginBottom: '10px' }}>
        <input
          type="text"
          value={inputText}
          onChange={(e) => setInputText(e.target.value)}
          onKeyPress={(e) => e.key === 'Enter' && handleSend()}
          placeholder="输入弹幕内容..."
          style={{ flex: 1, padding: '8px', fontSize: '14px' }}
        />
        <button onClick={handleSend}>发送</button>
        <button onClick={clearBarrages}>清空</button>
      </div>
      
      <div style={{ fontSize: '12px', color: '#666' }}>
        弹幕数量: {activeCount} / {maxCapacity}
      </div>
    </div>
  )
}

// 带API集成的高级示例
export const AdvancedBarrageExample: React.FC = () => {
  const videoRef = useRef<HTMLVideoElement>(null)
  const [inputText, setInputText] = useState('')
  const [barrages, setBarrages] = useState<BarrageData[]>([])
  const [currentVideoId] = useState('demo-video')
  
  // 配置API
  useEffect(() => {
    // setApiBaseUrl('http://localhost:3001') // 设置你的后端地址
    loadBarrages()
  }, [])

  const { barrageRef, addBarrage, clearBarrages } = useBarrage({
    config: {
      ...getPreset('default'),
      faceDetection: true,  // 启用人体检测
      showSkeleton: false   // 隐藏骨架线
    },
    events: {
      onAdd: (barrage) => console.log('弹幕添加:', barrage.text),
      onRemove: (barrage) => console.log('弹幕移除:', barrage.text)
    }
  })

  const loadBarrages = async () => {
    try {
      const result = await BarrageAPI.getBarragesByVideo(currentVideoId)
      if (result.success) {
        setBarrages(result.data || [])
      }
    } catch (error) {
      console.log('加载弹幕失败，使用本地模式')
    }
  }

  const sendBarrage = async () => {
    if (!inputText.trim()) return

    // 本地显示
    const barrage = createBarrage(inputText, {
      color: '#4ECDC4',
      fontSize: 20
    })
    addBarrage(barrage)

    // 发送到服务器
    try {
      const result = await BarrageAPI.sendBarrage({
        text: inputText,
        color: '#4ECDC4',
        videoId: currentVideoId,
        time: videoRef.current?.currentTime || 0,
        type: 'scroll',
        fontSize: 20,
        user: '用户' + Math.floor(Math.random() * 1000)
      })
      
      if (result.success) {
        console.log('弹幕发送成功')
        loadBarrages() // 重新加载弹幕列表
      }
    } catch (error) {
      console.log('服务器不可用，仅本地显示')
    }

    setInputText('')
  }

  const generateTestBarrages = () => {
    const testTexts = [
      '太精彩了！', '666', '这个镜头绝了', 'Amazing!', 
      '弹幕测试', 'Hello World', '人体检测真厉害', '自动避让功能'
    ]
    
    testTexts.forEach((text, index) => {
      setTimeout(() => {
        const barrage = createBarrage(text, {
          color: `hsl(${index * 45}, 70%, 50%)`,
          fontSize: 18 + Math.random() * 8
        })
        addBarrage(barrage)
      }, index * 500)
    })
  }

  return (
    <div style={{ maxWidth: '900px', margin: '0 auto', padding: '20px' }}>
      <h2>高级弹幕示例 (带API和AI检测)</h2>
      
      <div style={{ position: 'relative', marginBottom: '20px' }}>
        <video
          ref={videoRef}
          src="/demo-video.mp4" // 替换为你的视频路径
          controls
          style={{ width: '100%', height: '500px', objectFit: 'contain' }}
        />
        
        <VideoBarrage
          ref={barrageRef}
          videoRef={videoRef}
          config={{
            ...getPreset('default'),
            faceDetection: true,
            showSkeleton: false
          }}
          enabled={true}
        />
      </div>
      
      <div style={{ display: 'flex', gap: '10px', marginBottom: '15px' }}>
        <input
          type="text"
          value={inputText}
          onChange={(e) => setInputText(e.target.value)}
          onKeyPress={(e) => e.key === 'Enter' && sendBarrage()}
          placeholder="输入弹幕内容..."
          style={{ flex: 1, padding: '10px', fontSize: '14px' }}
        />
        <button onClick={sendBarrage} style={{ padding: '10px 20px' }}>
          发送
        </button>
        <button onClick={clearBarrages} style={{ padding: '10px 20px' }}>
          清空
        </button>
        <button onClick={generateTestBarrages} style={{ padding: '10px 20px' }}>
          测试弹幕
        </button>
      </div>
      
      <div style={{ 
        display: 'grid', 
        gridTemplateColumns: '1fr 1fr', 
        gap: '20px',
        fontSize: '12px',
        color: '#666'
      }}>
        <div>
          <strong>功能状态:</strong>
          <br />✅ 基础弹幕渲染
          <br />✅ 人体检测避让
          <br />✅ API数据同步
          <br />✅ 响应式适配
        </div>
        <div>
          <strong>弹幕统计:</strong>
          <br />数据库弹幕: {barrages.length} 条
          <br />当前视频: {currentVideoId}
          <br />检测状态: 已启用
        </div>
      </div>
    </div>
  )
}

// 移动端优化示例
export const MobileBarrageExample: React.FC = () => {
  const videoRef = useRef<HTMLVideoElement>(null)
  const [inputText, setInputText] = useState('')
  
  const { barrageRef, addBarrage } = useBarrage({
    config: getPreset('mobile') // 使用移动端优化配置
  })

  const quickSend = (text: string) => {
    const barrage = createBarrage(text, {
      color: '#FF6B6B',
      fontSize: 16
    })
    addBarrage(barrage)
  }

  return (
    <div style={{ maxWidth: '100%', padding: '10px' }}>
      <h3>移动端弹幕示例</h3>
      
      <div style={{ position: 'relative', marginBottom: '15px' }}>
        <video
          ref={videoRef}
          src="/demo-video.mp4"
          controls
          style={{ width: '100%', height: 'auto' }}
        />
        
        <VideoBarrage
          ref={barrageRef}
          videoRef={videoRef}
          config={getPreset('mobile')}
          enabled={true}
        />
      </div>
      
      {/* 快捷弹幕按钮 */}
      <div style={{ 
        display: 'flex', 
        flexWrap: 'wrap', 
        gap: '8px', 
        marginBottom: '10px' 
      }}>
        {['666', '哈哈哈', '太棒了', '👍', '❤️', '🔥'].map(text => (
          <button
            key={text}
            onClick={() => quickSend(text)}
            style={{ 
              padding: '6px 12px', 
              fontSize: '12px',
              borderRadius: '15px',
              border: '1px solid #ddd',
              background: '#f8f9fa'
            }}
          >
            {text}
          </button>
        ))}
      </div>
      
      {/* 自定义输入 */}
      <div style={{ display: 'flex', gap: '8px' }}>
        <input
          type="text"
          value={inputText}
          onChange={(e) => setInputText(e.target.value)}
          placeholder="自定义弹幕..."
          style={{ 
            flex: 1, 
            padding: '8px', 
            fontSize: '14px',
            borderRadius: '4px',
            border: '1px solid #ddd'
          }}
        />
        <button 
          onClick={() => {
            if (inputText.trim()) {
              quickSend(inputText)
              setInputText('')
            }
          }}
          style={{ padding: '8px 16px' }}
        >
          发送
        </button>
      </div>
    </div>
  )
}

// 默认导出组合示例
const BarrageExamples: React.FC = () => {
  const [currentExample, setCurrentExample] = useState<'basic' | 'advanced' | 'mobile'>('basic')

  return (
    <div>
      <div style={{ 
        textAlign: 'center', 
        marginBottom: '30px',
        borderBottom: '1px solid #eee',
        paddingBottom: '20px'
      }}>
        <h1>🎯 弹幕组件库示例</h1>
        <div style={{ display: 'flex', justifyContent: 'center', gap: '10px' }}>
          <button 
            onClick={() => setCurrentExample('basic')}
            style={{ 
              padding: '8px 16px',
              backgroundColor: currentExample === 'basic' ? '#007bff' : '#f8f9fa',
              color: currentExample === 'basic' ? 'white' : 'black'
            }}
          >
            基础示例
          </button>
          <button 
            onClick={() => setCurrentExample('advanced')}
            style={{ 
              padding: '8px 16px',
              backgroundColor: currentExample === 'advanced' ? '#007bff' : '#f8f9fa',
              color: currentExample === 'advanced' ? 'white' : 'black'
            }}
          >
            高级示例
          </button>
          <button 
            onClick={() => setCurrentExample('mobile')}
            style={{ 
              padding: '8px 16px',
              backgroundColor: currentExample === 'mobile' ? '#007bff' : '#f8f9fa',
              color: currentExample === 'mobile' ? 'white' : 'black'
            }}
          >
            移动端示例
          </button>
        </div>
      </div>

      {currentExample === 'basic' && <BasicBarrageExample />}
      {currentExample === 'advanced' && <AdvancedBarrageExample />}
      {currentExample === 'mobile' && <MobileBarrageExample />}
    </div>
  )
}

export default BarrageExamples
